/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int getDeep(TreeNode *root) {
        if (root == NULL) return 0;
        int l_deep = getDeep(root->left);
        int r_deep = getDeep(root->right);
        if (l_deep == -1 || r_deep == -1) return -1;
        if (abs(l_deep - r_deep) > 1) return -1;
        return max(l_deep, r_deep) + 1;
    }
    bool isBalanced(TreeNode* root) {
        if (root == NULL) return true;
        int l_deep = getDeep(root->left);
        int r_deep = getDeep(root->right);
        if (l_deep == -1 || r_deep == -1) return false;
        if (abs(l_deep - r_deep) > 1) return false;
        return true;
    }
};
